// ==UserScript==
// @name         hactcm auto watch
// @namespace    https://scriptcat.org/zh-CN/
// @version      0.1.0
// @description  中医药大学自动看课
// @author       jjuker
// @match        *://lms.hactcm.edu.cn/venus/*
// ==/UserScript==

(function () {
    'use strict';

    const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
    const random = (max, min = 3000) => Math.floor(Math.random() * (max - min + 1)) + min;

    // 添加日志函数
    function logger(message) {
        console.log(`[hactcm-auto-watch] ${message}`);
    }

    async function waitForFunction(fn = () => null, timeout = 10000) {
        const start = Date.now();
        while (Date.now() - start < timeout) {
            const result = fn();
            if (result) return result;
            await sleep(500);
        }
        throw new Error(`failed to wait for function`);
    }

    function setupHashChangeListener(callback) {
        let lastHash = location.hash;
        const observer = new MutationObserver(() => {
            if (lastHash !== location.hash) {
                lastHash = location.hash;
                callback();
            }
        });
        observer.observe(document, {
            subtree: true,
            childList: true,
            attributes: true,
            attributeFilter: ['href']
        });
        return observer;
    }

    async function getVideo() {
        try {
            return await waitForFunction(() => unsafeWindow.vplayer)
        } catch (e) {
            logger('No video found, continuing');
            return null;
        }
    }

    async function playVideo(vplayer) {
        return new Promise((resolve, reject) => {
            vplayer.on('ended', resolve)
            vplayer.on('error', reject)
            vplayer.on('canplaythrough', () => {
                logger('canplaythrough')
                // vplayer.currentTime(vplayer.duration() - 10)
                vplayer.play()
                vplayer.off('canplaythrough')
            })
        });
    }

    async function nextPage() {
        try {
            logger('Navigating to next page');
            const nextFn = await waitForFunction(() => unsafeWindow?.doNext);
            nextFn?.();
        } catch (e) {
            logger('Cannot find next Function');
        }
    }


    let isRunning = false;
    async function start() {
        if (isRunning) {
            logger('Script isRunning');
            return;
        }
        isRunning = true;
        logger('Script started');

        try {
            logger('Waiting');
            await sleep(5800);
            logger('running');

            const video = await getVideo();
            if (video) {
                logger('Video found, starting playback');
                await playVideo(video).catch(e => logger(`Video playback error: ${e.message}`));
            }

            await sleep(random(15000, 5000));
            await nextPage();
            logger('Script completed');
        } catch (e) {
            logger(`Fatal error: ${e.message}`);
        } finally {
            logger('Script finished');
            isRunning = false;
        }
    }

    // 启动
    let hashObserver;
    window.addEventListener('load', () => {
        start();
        hashObserver = setupHashChangeListener(() => {
            logger('Page hash changed, restarting script');
            sleep(1000).then(() => {
                logger('Restarting script');
                if (!isRunning) start();
            });
        });
    });

    // 卸载
    window.addEventListener('unload', () => {
        if (hashObserver) {
            hashObserver.disconnect();
        }
    });
})();